package cn.ibizlab.odoo.util.valuerule;

import org.springframework.lang.Nullable;

/**
 * 字符长度（STRINGLENGTH）值规则
 */
public class StringLengthValueRule {

    /**
     * 字符串长度是否合法
     *
     * @param value        校验值，Object
     * @param minlength    最大值
     * @param maxlength    最小值
     * @param isIncludeMin  是否包含最小值
     * @param isIncludeMax  是否包含最大值
     * @return  true/false
     */
    public static boolean isValid(Object value, @Nullable Integer minlength,@Nullable Integer maxlength,
                                  @Nullable Boolean isIncludeMin,@Nullable Boolean isIncludeMax) {
        if (value == null) {
            return false;
        }
        boolean isInRange = true;
        int length = String.valueOf(value).length();

        //最小值比较
        if (minlength != null) {
            if (isIncludeMin == null || !isIncludeMin) {
                isInRange = isInRange && (length > minlength);
            } else {
                isInRange = isInRange && (length >= minlength);
            }
        }

        //最大值比较
        if (maxlength != null) {
            if (isIncludeMax == null || !isIncludeMax) {
                isInRange = isInRange && (length < maxlength);
            } else {
                isInRange = isInRange && (length <= maxlength);
            }
        }
        return isInRange;
    }
}
